package com.ruoyi.warning.ding;

import com.alibaba.fastjson2.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;

import java.io.File;

public class DingTalkMediaUploadUtils {

    private static final String UPLOAD_MEDIA_URL = "https://oapi.dingtalk.com/media/upload";
    private static final String DEFAULT_APP_KEY = "dingwzsuuwkhxmzp6cnu";
    private static final String DEFAULT_APP_SECRET = "h8KWqrCgAjUO0IWSVLC7GWcEVqHGhElE_A9e_huX2UyATapcNb3Z0GxiHh37BkmJ";

    public static String uploadMedia(String accessToken, String mediaType, File file) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(UPLOAD_MEDIA_URL);
        OapiMediaUploadRequest request = new OapiMediaUploadRequest();
        request.setType(mediaType);
        FileItem fileItem = new FileItem(file);
        request.setMedia(fileItem);

        OapiMediaUploadResponse response = client.execute(request, accessToken);
        if (response.isSuccess()) {
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            return jsonObject.getString("media_id");
        } else {
            System.err.println("上传媒体文件失败: " + response.getErrmsg());
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            // 假设已经获取到 accessToken
//            String accessToken = getAccessToken("edaf3fbf463336c89d5631945c86fb96");
            String accessToken = "edaf3fbf463336c89d5631945c86fb96";
            // 媒体类型，例如 "image"
            String mediaType = "image";
            // 要上传的文件
            File file = new File("C:\\Users\\SanS1\\Desktop\\微信截图_20250219104825.png");
            String mediaId = uploadMedia(accessToken, mediaType, file);
            if (mediaId != null) {
                System.out.println("MediaId: " + mediaId);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

}

